﻿using System.Linq;
using System.Web.Mvc;
using KLS.PPDS.Utility;
using log4net;

namespace KLS.PPDS.Utilities.BaseController
{
    [HandleError]
    //[AjaxAuthorize]
    public class BaseController : Controller
    {


        /// <summary>
        /// return json message
        /// </summary>
        /// <param name="messgae"></param>
        /// <returns></returns>
        public JsonResult JsonMessage(string messgae) 
        {
            return new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,

                Data = new
                {
                    Message = messgae,
                    StackTrace = messgae,
                    Result = true
                }
            };
        }

        private static readonly ILog log = LogManager.GetLogger(typeof(BaseController));
        /// <summary>
        /// This is controller common error handler
        /// for showing error message please use OnComplete/OnSucess method to receve json error message
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {

            if (filterContext == null)
            {
                return;
            }
            if (filterContext.Exception != null)
            {
               // filterContext.Exception.ErrorLog();
                log.Error(filterContext.Exception);
            }



          //  var ctx = filterContext.HttpContext;

           

            


            //// check if session is supported 
            //if (ctx.Session != null && ctx.Session.IsNewSession)
            //{
            //    // If it says it is a new session, but an existing cookie exists, then it must 
            //    // have timed out 
            //    string sessionCookie = ctx.Request.Headers["Cookie"];
            //    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
            //    {
            //        //FormsAuthentication.SignOut();
            //        //ctx.Response.Redirect("~/Login/Logout");
            //        //return;

            //        filterContext.Result = new JavaScriptResult()
            //                                   {
            //                                       Script = "LogOut();"
            //                                   };  

                    
            //        filterContext.ExceptionHandled = true;

            //       // filterContext.Result = RedirectToAction("Logout", "Login");
            //        return;
            //    }
            //}

            //var chk = ctx.Session["SessionStart"];

            //if (chk == null)
            //{
            //    filterContext.Result = new JavaScriptResult()
            //    {
            //        Script = "LogOut();"
            //    };

            //    filterContext.ExceptionHandled = true;
            //    return;
            //}


            if ((filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null) || filterContext.Exception != null)
            {
                filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                

                filterContext.Result = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    
                    Data = new
                    {
                        Message = filterContext.Exception.Message,
                        StackTrace = filterContext.Exception.StackTrace,
                        Result = true
                    }
                };
                filterContext.ExceptionHandled = true;
            }
            
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (Session["LoggedIn"] == null) //if user not authenticated it will return to login page
            {
                if (Request.IsAjaxRequest())
                {
                    filterContext.Result = new JavaScriptResult() {Script = "LogOut();"};
                }
                else
                {
                  filterContext.Result = RedirectToAction("Index", "Login"); 
                }

             
            }
            //else if (Request.IsAjaxRequest()==false && TempData["AjaxRequest"] == null)
            //{
                
            //    filterContext.Result = RedirectToAction("Index", "Home");
            //}
            else
            {
                base.OnActionExecuting(filterContext);
                this.SetUiCulture();     
            }
            
        
        }

        //protected override void OnResultExecuting(ResultExecutingContext filterContext)
        //{
        //    this.SetUiCulture();
        //    base.OnResultExecuting(filterContext);
        //}

        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (filterContext.Result is RedirectToRouteResult)
            {
                //Request.IsAjaxRequest() does not work always... i.e RedirectToAction
                TempData["AjaxRequest"] = Request.IsAjaxRequest();
            }
            else
            {
                TempData["AjaxRequest"] = null;
            }

            
        }

        private void SetUiCulture()
        {
            if (CommonSession.UserId == 0)
            {
                if (Request != null)
                {
                    if (Request.UserLanguages != null)
                        if (Request.UserLanguages.Count() > 0)
                        {
                            var browserLanguage = Request.UserLanguages[0];
                            CommonTask.SetCulture(browserLanguage);


                        }
                }
            }
            else
            {
              CommonTask.SetCulture(CommonSession.Language);
            }


        }


    }
}
